<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Resources\Admin\RoleResource;
use App\Repositories\Admin\RoleRepository;
use App\Services\RoleService;
use Illuminate\Http\Request;
use App\Http\Controllers\ApiController;

/**
 * Class RoleController
 * @package App\Http\Controllers\Api\Admin\User
 */
class RoleController extends ApiController
{

    /**
     * @var RoleService
     */
    private $service;


    /**
     * @var RoleRepository
     */
    private $repo;

    /**
     * RoleController constructor.
     * @param RoleService $service
     * @param RoleRepository $repo
     */
    public function __construct(RoleService $service, RoleRepository $repo)
    {
        $this->service = $service;
        $this->repo = $repo;
        $this->middleware('jwt:admin');
    }

    /**
     * 获取列表信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $this->hasPermission('role-main');
        $map = $request->all();
        $list = $this->service->seek($map);
        return $this->success(RoleResource::collection($list));
    }

    /**
     * 获取详情
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id)
    {
        $this->hasPermission('role-main');
        $info = $this->service->find($id);
        $info->permission_id = $info->permissions()->pluck('id');
        $info->menus_id = $info->menus()->pluck('id');
        return $this->success(new RoleResource($info));
    }


    /**
     * 修改
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $this->hasPermission('role-opera');
        $info = $this->repo->doCreate($request->all());
        return $this->success(new RoleResource($info));
    }

    /**
     * @param $id
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update($id, Request $request)
    {
        $this->hasPermission('role-opera');
        $data = $request->all();
        $info = $this->repo->doUpdate($data, $id);
        return $this->success(new RoleResource($info));
    }

    /**
     * 删除记录
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        $this->hasPermission('role-del');
        $this->service->delete($id);
        return $this->message('删除成功！');
    }
}
